package com.GroupSix.service;


import com.GroupSix.dao.DictDao;
import com.GroupSix.dao.StudentDao;
import com.GroupSix.entity.DictEntity;
import com.GroupSix.entity.StudentEntity;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import static com.GroupSix.tool.PasswordUtil.Md5;
import static com.GroupSix.tool.PasswordUtil.isValidPassword;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;


@Service("studentService")
public class StudentServiceImpl extends ServiceImpl<StudentDao, StudentEntity>
        implements StudentService {

    //注入数据字典
    @Autowired
    private DictDao dictDao;

    //实现增
    @Override
    public  Integer add(StudentEntity stu){
        stu.setStudentPassword(Md5(stu.getStudentPassword()));//使用MD5对密码进行加密
        if(stu.getIsActive()==null) {
            stu.setIsActive(0);
        }
        if(stu.getUpdateTime()==null) {
            stu.setUpdateTime(LocalDateTime.now());
        }
        if(stu.getCreateTime()==null){
            stu.setCreateTime(LocalDateTime.now());
        }
        return baseMapper.insert(stu);
    }

    //学生用户注册
    @Override
    public  String signUp(String name, Integer id, String pwd, String stuClass){
        QueryWrapper<StudentEntity> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("student_name",name);
        queryWrapper1.eq("student_id",id);
        if(baseMapper.selectCount(queryWrapper1)>0) {
            return "注册失败，用户名或账号已经存在";
        }
        else if(!isValidPassword(pwd)) {
            return "注册失败，密码必须同时包含大小写字母，数字和至少一个特殊符号";
        }
        else {
            QueryWrapper<DictEntity> queryWrapper2 = new QueryWrapper<>();
            queryWrapper2.eq("dict_name",stuClass);
            StudentEntity stu = new StudentEntity();
            stu.setStudentName(name);
            stu.setStudentId(id);
            stu.setStudentPassword(Md5(pwd));
            stu.setStudentClass(dictDao.selectOne(queryWrapper2).getId());
            stu.setIsActive(0);
            stu.setLoginTag(0);
            stu.setUpdateTime(LocalDateTime.now());
            stu.setCreateTime(LocalDateTime.now());
            stu.setLoginTime(LocalDateTime.now());
            baseMapper.insert(stu);
            return "注册成功";
        }
    }


    //实现删（根据id）
    @Override
    public Integer delete(Integer stuId){
        QueryWrapper<StudentEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id",stuId);
        if(baseMapper.selectCount(queryWrapper)>0) {
            return baseMapper.deleteById(baseMapper.selectOne(queryWrapper).getId());
        }
        else{
            return 0;
        }
    }

    //实现改(根据id)
    @Override
    public Integer update(StudentEntity stu){
        stu.setStudentPassword(Md5(stu.getStudentPassword()));//使用MD5对密码进行加密
        stu.setIsActive(0);
        stu.setLoginTag(0);
        stu.setUpdateTime(LocalDateTime.now());
        stu.setCreateTime(this.getById(stu.getId()).getUpdateTime());
        stu.setLoginTime(this.getById(stu.getId()).getLoginTime());
        return baseMapper.updateById(stu);
    }

    //分页查询
    @Override
    public IPage<StudentEntity> list(StudentEntity studentEntity, Integer pageNo, Integer pageSize){
        LambdaQueryWrapper<StudentEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(StudentEntity::getId, studentEntity.getId());

        int currentPage = 1;
        int limit = 10;
        if (pageNo != null && pageNo > 0) {
            currentPage = pageNo;
        }
        if (pageSize != null && pageSize > 0) {
            limit = pageSize;
        }

        IPage<StudentEntity> page = Page.of(currentPage, limit);

        return baseMapper.selectPage(page, wrapper);
    }

    //根据学号查询
    @Override
    public StudentEntity getByStudentId(Integer id){
        QueryWrapper<StudentEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("student_id", id);
        return baseMapper.selectOne(wrapper);
    }

    //根据姓名查询
    @Override
    public StudentEntity getByStudentName(String studentName){
        QueryWrapper<StudentEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("student_name", studentName);
        return baseMapper.selectOne(wrapper);
    }

    //学生登录
    @Override
    public String login(String stuName,Integer stuId, String stuPwd) {
        QueryWrapper<StudentEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("student_name", stuName);
        wrapper.eq("student_id", stuId);
        if(baseMapper.selectCount(wrapper)>0) {
            StudentEntity stu = baseMapper.selectOne(wrapper);
            wrapper.eq("student_password", Md5(stuPwd));
            Long t = Duration.between(stu.getLoginTime(), LocalDateTime.now()).getSeconds();
            if(baseMapper.selectCount(wrapper)>0&&(stu.getLoginTag()!=3||t>=30)) {
                stu.setLoginTag(0);
                stu.setLoginTime(LocalDateTime.now());
                baseMapper.updateById(stu);
                return "登录成功";
            }
            else if(stu.getLoginTag()==3&&t<30) {
                    return "请"+(30-t)+"秒后重试";
            }
            else {
                if(stu.getLoginTag()==3){
                    stu.setLoginTag(0);
                }
                int i = stu.getLoginTag();
                stu.setLoginTag(i+1);
                stu.setLoginTime(LocalDateTime.now());
                baseMapper.updateById(stu);
                return "密码错误,连续错误3次后将在30秒内无法重新登录";
            }
        }
        else{
            return "登录失败，请检查用户名或学号是否正确";
        }
    }

}
